package com.woniuxy.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * MyBatis工具类,封装SqlSession对象的创建
 */
public class MyBatisUtil {
    //SqlSessionFactory,只创建一次
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession() {
        SqlSession sqlSession=null;
        try {
            //加载主配置文件，resources的目录会自动读取
            SqlSessionFactory sqlSessionFactory =
                    null;
            if (sqlSession==null) {
                InputStream inputStream =
                Resources.getResourceAsStream("mybatis-config.xml");
                //SqlSessionFactoryBuilder,创建SqlSessionFactory
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }
            //SqlSessionFactoryBuilder,创建SqlSession
            sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
